package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.PasswordEncoder;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;
import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Primary
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result sendCode(String phone, HttpSession session) {
        // 1. 生成验证码
        String code = RandomUtil.randomNumbers(6);
        // 2. 保存验证码到 redis
        stringRedisTemplate.opsForValue().set(LOGIN_CODE_KEY + phone, code, LOGIN_CODE_TTL, TimeUnit.MINUTES);
        // session.setAttribute(phone, code);
        // 3. 发送验证码
        log.debug("发送短信验证码成功，验证码：{}", code);
        // 4. 返回成功
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        // 1. 从 redis 获取验证码并校验
        String phone = loginForm.getPhone();
        String password = loginForm.getPassword();

        // 校验验证码
        String cacheCode = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + phone);
        if (StrUtil.isNotBlank(cacheCode)) {
            stringRedisTemplate.delete(LOGIN_CODE_KEY + phone);
            if (!cacheCode.equals(loginForm.getCode())) {
                return Result.fail("验证码错误");
            }
            // 验证码登录成功
            return handleSmsLogin(phone);
        }
        if (StrUtil.isNotBlank(password)) {
            // 密码登录
            return handlePasswordLogin(phone, password);
        }
        return Result.fail("登录失败");
    }

    @Override
    public Result logout(HttpServletRequest request) {
        // 1.从请求头中获取token
        String token = request.getHeader("authorization");
        // 2.获取当前用户信息
        String nickName = UserHolder.getUser().getNickName();
        stringRedisTemplate.delete(LOGIN_USER_KEY + token);
        log.info(LocalTime.now() + "用户：{}，退出成功", nickName);
        return Result.ok();
    }

    // 签到
    @Override
    public Result sign() {
        // 1.获取当前登录用户
        Long userId = UserHolder.getUser().getId();
        // 2.获取当前日期
        LocalDateTime now = LocalDateTime.now();
        // 3.拼接key
        String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyy:MM"));
        String key = USER_SIGN_KEY + userId + keySuffix;
        // 4.获取今天是本月的第几天
        int dayOfMonth = now.getDayOfMonth();
        // 5.写入redis SETBIT key offset 1
        stringRedisTemplate.opsForValue().setBit(key, dayOfMonth - 1, true);
        return Result.ok();
    }

    @Override
    public Result signCount() {
        // 1.获取当前登录用户
        Long userId = UserHolder.getUser().getId();
        // 2.获取当前日期
        LocalDateTime now = LocalDateTime.now();
        // 3.拼接key
        String keySuffix = now.format(DateTimeFormatter.ofPattern(":yyyy:MM"));
        String key = USER_SIGN_KEY + userId + keySuffix;
        // 4.获取今天是本月的第几天
        int dayOfMonth = now.getDayOfMonth();
        // 5.获取本月截止今天为止的所有的签到记录，返回的是一个十进制数字
        List<Long> results = stringRedisTemplate.opsForValue().bitField(key, BitFieldSubCommands.create()
                .get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth)).valueAt(0));

        if (results == null || results.size() == 0) {
            return Result.ok(0);
        }
        Long result = results.get(0);
        if (result == null || result == 0) {
            return Result.ok(0);
        }
        // 6.result与1进行按位与运算，得到一个数字，判断这个数字的二进制连续表示中1的个数
        Integer dayCount = 0;

        // 判断当天有没有签到
        if ((result & 1) == 1) {
            // 当天签到 dayCount+1
            dayCount++;
        }
        // 判断完当天是否签到后右移一位
        result >>>= 1;

        // 过去几天连续签到次数
        while (result != 0) {
            if ((result & 1) == 0) {
                // 没有签到
                break;
            }
            dayCount++;
            result >>>= 1;
        }

        return Result.ok(dayCount);
    }

    private Result handleSmsLogin(String phone) {
        // 2. 判断用户是否存在
        User user = query().eq("phone", phone).one();

        if (user == null) {
            // 新用户注册
            user = new User();
            user.setPhone(phone);
            user.setNickName(USER_NICK_NAME_PREFIX + RandomUtil.randomString(10));
            try {
                save(user);
            } catch (Exception e) {
                log.error("新用户注册失败: {}", e.getMessage(), e);
                return Result.fail("系统错误，请稍后再试");
            }
        }

        // 3. 保存用户到 redis
        return saveUserToRedis(user);
    }

    private Result handlePasswordLogin(String phone, String password) {
        // 2. 判断用户是否存在并验证密码
        User user = query().eq("phone", phone).one();

        if (user == null) {
            log.warn("用户不存在: {}", phone);
            return Result.fail("用户不存在");
        }

        // 验证密码
        String pwd = user.getPassword();
        if (StrUtil.isBlank(pwd)) {
            return Result.fail("用户未设置密码");
        }
        if (!PasswordEncoder.matches(password, pwd)) {
            log.warn("密码错误: {}", phone);
            return Result.fail("密码错误");
        }

        // 3. 保存用户到 redis
        return saveUserToRedis(user);
    }

    private Result saveUserToRedis(User user) {
        // 3.1. 生成随机 token，作为登录令牌
        String token = UUID.randomUUID().toString(true);
        // 3.2. 将用户信息转为 JSON 存入 redis
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);

        /*Map<String, String> map = new HashMap<>();
        map.put("id", String.valueOf(userDTO.getId()));
        map.put("nickName", userDTO.getNickName());
        map.put("icon", userDTO.getIcon());*/

        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(), CopyOptions.create()
                .setIgnoreNullValue(true)
                .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));

        stringRedisTemplate.opsForHash().putAll(LOGIN_USER_KEY + token, userMap);
        // 3.3. 设置 token 的过期时间
        // stringRedisTemplate.expire(LOGIN_USER_KEY + token, LOGIN_USER_TTL, TimeUnit.MINUTES);

        return Result.ok(token);
    }


}
